package com.ty.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator;

@Component  //1. 放入IOC容器中
@Slf4j
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(AbstractNameValueGatewayFilterFactory.NameValueConfig config) {
        String value = config.getValue();
        Long time_span = Long.parseLong(value);
        return (exchange, chain) -> {
            long stateTime = System.currentTimeMillis();
            //调用业务之前，先记下时间
            //下一个节点执行
           return chain.filter(exchange).then(Mono.fromRunnable(()->{
               long endTime = System.currentTimeMillis();
               long time = endTime - stateTime;
               if ( time> time_span) {
                   log.warn(StrUtil.format("请求耗时{}ms,请求路径{}", time,exchange.getRequest().getURI()));
               }
           }));

        };
    }
}

/*
return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
                ServerHttpRequest request = exchange.getRequest().mutate()
                        .headers(httpHeaders->httpHeaders.add(config.getName(),value))
                        .build();
                return chain.filter(exchange.mutate().request(request).build());
            }

            @Override
            public String toString() {
                return filterToStringCreator(LogTimeGatewayFilterFactory.this)
                        .append(config.getName(), config.getValue()).toString();


            }

        };
 */